package com.xls.dormitoryservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xls.base.annotation.Log;
import com.xls.commonutils.Result;
import com.xls.dormitoryservice.entity.Goods;
import com.xls.dormitoryservice.service.GoodsService;
import com.xls.dormitoryservice.vo.GoodsQuery;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xls
 * @since 2021-03-23
 */
@RestController
@RequestMapping("/dormitory/goods")
@Api(value = "物品信息接口")
@Slf4j
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Log(title = "物品管理", businessType = "查询")
    @PreAuthorize("hasAnyAuthority('dormitory:goods:list')")
    @GetMapping("/getGoods/{id}")
    public Result<Goods> getGoods(@PathVariable String id) {
        return Result.success(goodsService.getById(id));
    }

    @Log(title = "物品管理", businessType = "查询")
    @PreAuthorize("hasAnyAuthority('dormitory:goods:list')")
    @PostMapping("/list/{page}/{limit}")
    public Result<Page<Goods>> list(@PathVariable Integer page, @PathVariable Integer limit,
                                    @RequestBody GoodsQuery goodsQuery) {
        QueryWrapper<Goods> goodsQueryWrapper = new QueryWrapper<>();
        String goodsNo = goodsQuery.getGoodsNo();
        String goodsName = goodsQuery.getGoodsName();
        String begin = goodsQuery.getBegin();
        String end = goodsQuery.getEnd();
        goodsQueryWrapper.eq(!StringUtils.isEmpty(goodsNo), "goods_no", goodsNo)
                .likeRight(!StringUtils.isEmpty(goodsName), "goods_name", goodsName)
                .gt(!StringUtils.isEmpty(begin), "gmt_create", begin)
                .lt(!StringUtils.isEmpty(end), "gmt_modified", end)
                .eq("is_deleted", 0);
        return Result.success(goodsService.page(new Page<>(page, limit), goodsQueryWrapper));
    }

    @Log(title = "物品管理", businessType = "保存")
    @PreAuthorize("hasAnyAuthority('dormitory:goods:save')")
    @PostMapping("/save")
    public Result<Goods> save(@RequestBody Goods goods) {
        return goodsService.saveOrUpdate(goods) ? Result.success(goods) : Result.error();
    }

    @Log(title = "物品管理", businessType = "删除")
    @PreAuthorize("hasAnyAuthority('dormitory:goods:remove')")
    @DeleteMapping("/remove/{id}")
    public Result<Goods> remove(@PathVariable String id) {
        return goodsService.removeById(id) ? Result.success() : Result.error();
    }

}

